<template>
  <div class="locker-management">
    <el-button type="primary" @click="showAddLockerDialog">添加快递柜</el-button>
    <el-table :data="lockers" style="width: 100%">
      <el-table-column prop="id" label="快递柜ID"/>
      <el-table-column prop="location" label="位置"/>
      <el-table-column prop="status" label="状态"/>
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button @click="editLocker(scope.row)">编辑</el-button>
          <el-button type="danger" @click="deleteLocker(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <LockerDialog
        v-model="dialogVisible"
        :currentLocker="currentLocker"
        @submit="handleLockerSubmit"
    />
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue';
import {useStore} from 'vuex';
import LockerDialog from './dialog/LockerDialog.vue'; // 假设有一个快递柜对话框组件

const store = useStore();
const dialogVisible = ref(false);
const currentLocker = ref(null);

const lockers = computed(() => store.state.lockers);

const fetchLockers = () => {
  store.dispatch('fetchLockers');
};

onMounted(() => {
  fetchLockers();
});

const showAddLockerDialog = () => {
  currentLocker.value = null; // 清空当前快递柜
  dialogVisible.value = true; // 显示对话框
};

const handleLockerSubmit = (lockerData) => {
  if (lockerData.id) {
    store.dispatch('updateLocker', lockerData).then(() => {
      dialogVisible.value = false; // 关闭对话框
      fetchLockers(); // 刷新快递柜列表
    });
  } else {
    store.dispatch('addLocker', lockerData).then(() => {
      dialogVisible.value = false; // 关闭对话框
      fetchLockers(); // 刷新快递柜列表
    });
  }
};

const deleteLocker = (lockerId) => {
  store.dispatch('deleteLocker', lockerId).then(() => {
    fetchLockers(); // 刷新快递柜列表
  });
};

const editLocker = (locker) => {
  currentLocker.value = locker; // 设置当前快递柜
  dialogVisible.value = true; // 显示对话框
};
</script>

<style scoped>
.locker-management {
  padding: 20px;
}
</style>